import constant from '../constant';
import { isObject } from '../utils/util'
import axios from 'axios'
import Vue from 'vue'
import router from '../router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    // baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
    timeout: 5000
});

axios.interceptors.request.use(config => {
    // 开启进度条
    NProgress.start()
    // 在发送请求之前做些什么，例如加入token
    console.log(`%c [${config.method.toUpperCase()}] ${config.url}`,'background:#FFA500; color:#FFFFFF', )
    return config
}, error => {
    // 对请求错误做些什么
    console.log(error);
    return Promise.reject(error)
})

axios.interceptors.response.use(response => {
    NProgress.done()
    // 在接收响应做些什么，例如跳转到登录页
    if (response.status === 200) {
        return response.data;
    } else {
        Promise.reject();
    }
}, error => {
    NProgress.done()
    console.log(error);
    return Promise.reject();
})


// 处理正常返回
export function response (res) {
    let result = null
    if (isObject(res)) {
        // 判断 code
        if (res.code) {
            if (res.code === constant.CODE.SUCCESS) {
                result = res.data ? res.data : null
            } else if (res.code === constant.CODE.NOT_LOGIN) {
                // 没有登录的情况
                Vue.prototype.$notify.error({
                    title: '错误:' + res.code,
                    message: res.message
                })
                setTimeout(() => {
                    router.replace({path: '/login'})
                }, 1000)
            } else {
                Vue.prototype.$notify.error({
                    title: '错误:' + res.code,
                    message: res.message
                })
            }
        } else {
            result = res
        }
    } else {
        result = { __state: true, data: res }
    }
    return result
}

// 处理异常错误
export function catchError (err, xhr, res) {
    if (res) {
        return {
            __state: false,
            code: res.status,
            message: res.error,
            timestamp: res.timestamp,
            url: xhr.responseURL
        }
    }
    // Vue.prototype.$message.error('网络故障')
    return {
        __state: false,
        isTimeout: /timeout/i.test(err.message),
        error: err
    }
}

function cleanArray(actual) {
    const newArray = []
    for (let i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i])
        }
    }
    return newArray
}

// json转换queryString
export function param(json) {
    if (!json) return ''
    return cleanArray(Object.keys(json).map(key => {
        if (json[key] === undefined || json[key] === null) return ''
        return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })).join('&')
}

// post请求
export function upload (uri, form) {
    return axios
        .post(uri, form)
        .then(response)
        .catch(catchError)
}

// post请求
export function post (uri, params, options) {
    return axios
        .post(uri, params, options)
        .then(response)
        .catch(catchError)
}

export function get (uri, options) {
    return axios
        .get(uri, options)
        .then(response)
        .catch(catchError)
}
